﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using TA.Entities;
using System.Collections;
using System.ComponentModel;
using TA.WebControls;
using TA.DotNetUtils;

public static class _ListControlExtensions
{
	public static void DataBind(this ListControl lcThis, object dataSource)
	{
		lcThis.DataBind(dataSource, "Id", "Name");
	}
	public static void DataBind(this ListControl lcThis, object dataSource, string valueField, string textField)
	{
		lcThis.DataBind(dataSource, valueField, textField, true);
	}
	public static void DataBind(this ListControl lcThis, object dataSource, string valueField, string textField, bool perform)
	{
		if (perform)
		{

			IEnumerable list;
			if (dataSource is IListSource)
			{
				IListSource ls = (IListSource)dataSource;
				list = ls.GetList();
			}
			else if (dataSource is IEnumerable)
				list = (IEnumerable)dataSource;
			else
				return;

			Formatter valueFormatter = new Formatter(valueField, true),
				textFormatter = new Formatter(textField, true);

			lcThis.GetType().GetMethod("TrackViewState",
				System.Reflection.BindingFlags.NonPublic
				| System.Reflection.BindingFlags.Instance
				//| System.Reflection.BindingFlags.
				).Invoke(lcThis, new object[0]);
			lcThis.Items.Clear();

			foreach (object o in list)
			{
				lcThis.Items.Add(new ListItem(textFormatter.GetString(o), valueFormatter.GetString(o)));
			}
		}
		else
		{
			lcThis.DataSource = dataSource;
			lcThis.DataValueField = valueField;
			lcThis.DataTextField = textField;
		}
	}
	public static T GetValue<T>(this ListControl lc) where T : ItemWithId<int>, new()
	{
		try
		{
			return new T { Id = int.Parse(lc.SelectedValue) };
		}
		catch
		{
			return null;
		}
	}
}
